package systemFile;

import general.ActionEnum;
import general.FileUtils;
import general.GlobalProperties;
import jsonObjects.Files;
import jsonObjects.Profile;
import org.apache.log4j.Logger;
import serverHandling.HttpRequestHandlers;
import serverHandling.SessionObjects;

import java.awt.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.TimerTask;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ScheduleSyncAlgorithm extends TimerTask {

    private static Logger log = Logger.getLogger(TimerTask.class);


    public void run() {
        try {
            ArrayList<Files> tmpFilesList;
            for (Profile prof : SessionObjects.getProfiles()) {
                // lista plikow lokalnych
                File dir = new File(GlobalProperties.getFolderMonit() + prof.getName());
                ArrayList<Files> localFiles = null;

                if (dir.exists()) {
                    File[] files = dir.listFiles();
                    localFiles = new ArrayList<Files>();

                    // plik .properties pomijany, wysylany dopiero na koniec synchronizacji
                    if (files != null)
                        for (File tmp : files)
                            if (!FileUtils.getExtension(tmp).equals("properties"))
                                localFiles.add(new Files(tmp.getName(), new Date(tmp.lastModified())));
                }


                tmpFilesList = HttpRequestHandlers.getListProfile(prof.getId());
                SessionObjects.addFilesToProfile(prof.getName(), (ArrayList<Files>) tmpFilesList.clone());
                HttpRequestHandlers.algorystSynchronizacjiWstepnej(tmpFilesList, localFiles, prof);

                // wysylanie pliku properties
                if (FileUtils.getProfilePropertyFile(prof).exists())
                    FileBuffer.getInstance().getListOfFile().put(FileUtils.getProfilePropertyFile(prof), ActionEnum.EDIT);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}
